"""
    进程相关操作
    进程通信Queue

"""
import queue
import time
from multiprocessing import Process, Lock, Queue
import os
import sys

lock = Lock()

#q.put()  写入
#q.get()  读取
#q.full() 队列是否满
#q.empty() 是否空
#q.qsize() 数量

q = Queue()
#自定义一个线程类
class MyProcess(Process):
    a = None
    b = None
    def __init__(self, name, *args, **kwargs):
        super().__init__(name=name, args=args)
        #self.name = name
        self.a = args[0]
        self.b = args[1]

    def run(self):
        time.sleep(1)
        with lock:
            #q.put(os.getpid())
            # 构建输出字符串
            output = f"进程号： {os.getpid():6d} {self.name} 执行run方法 a = {self.a} , b = {self.b}\n"
            # 使用 sys.stdout.write 输出并刷新缓冲区
            sys.stdout.write(output)
            sys.stdout.flush()

#生产着
class Producer(Process):
    a = None
    b = None
    q = None
    def __init__(self, name, queue, *args, **kwargs):
        super().__init__(name=name, args=args)
        self.q = queue

    def run(self):
        for i in range(20):
            time.sleep(0.5)
            self.q.put(f"数字：{i}")
            print(f"生产数字：{i}完成")
        # 生产结束后，向队列中放入 None 作为结束信号
        self.q.put(None)

# 消费着
class Consumer(Process):
    a = None
    b = None
    q = None
    def __init__(self, name, queue, *args, **kwargs):
        super().__init__(name=name, args=args)
        self.q = queue

    def run(self):
        while True:
            time.sleep(1)
            if self.q.empty():
                time.sleep(0.6)
                print("没吃的了")
            if self.q.get() is None:
                print("生产者下班了")
                self.q.put("给上级一个吃的")
                break
            else:
                print("拿到吃的：" + self.q.get())

if __name__ == '__main__':

    # 创建并启动线程，直接传递位置参数
    #t1 = MyProcess("进程1", 1, 2)  # 直接传递位置参数
    #t2 = MyProcess("线程2", 1, 2)  # 直接传递位置参数
    #t3 = MyProcess("线程3", 1, 2)  # 直接传递位置参数
    #t4 = MyProcess("线程4", 1, 2)  # 直接传递位置参数
    #t1.start()  # 启动线程
    #t2.start()
    #t3.start()
    #t4.start()

    #t1.join()
    #t2.join()
    #t3.join()
    #t4.join()



    t1 = Producer("进程1", q)
    t2 = Consumer("线程2", q)

    t1.start()
    t2.start()

    t1.join()
    print("t1.join()")
    t2.join()
    print("t2.join()")

    print(q.qsize())

    print("主线程执行完成")
